package com.cn.netty.http.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BusinessHandler extends ChannelInboundHandlerAdapter {


  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    log.info("request -> {}", msg);

    FullHttpRequest httpRequest = (FullHttpRequest) msg;
    ByteBuf content = httpRequest.content();
    log.info("body -> {}", content.toString(CharsetUtil.UTF_8));

    ByteBuf buf = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
    //响应体
    FullHttpResponse response
            = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "test/plain;charset=UTF-8");

    ChannelFuture channelFuture = ctx.writeAndFlush(response);
    channelFuture.addListener(ChannelFutureListener.CLOSE); //关闭

    httpRequest.release(); //释放 ByteBuf

  }

}
